package zheezes.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class ConstantUtil {
	public static final int K_MAP = 0;
	public static final int V_MAP = 1;
	
	public static final Map kmap(Class clazz) {
		return kmap(clazz, null);
	}

	public static final Map kmap(Class clazz, Collection<Class> types) {
		return kmap(clazz, types, null);
	}

	public static final Map kmap(Class clazz, Collection<Class> types, String regex) {
		return domap(clazz, types, regex, K_MAP);
	}
	
	public static final Map vmap(Class clazz) {
		return vmap(clazz, null);
	}

	public static final Map vmap(Class clazz, Collection<Class> types) {
		return vmap(clazz, types, null);
	}

	public static final Map vmap(Class clazz, Collection<Class> types, String regex) {
		return domap(clazz, types, regex, V_MAP);
	}
	
	private static final Map domap(Class clazz, Collection<Class> types, String regex, int mode) {
		Map map = new HashMap();
		for (Field field : clazz.getFields()) {
			if (types == null || types.contains(field.getType())) {
				if (regex == null || field.getName().matches(regex)) {
					int modifier = field.getModifiers();
					if ((modifier & (Modifier.STATIC | Modifier.FINAL)) != 0) {
						try {
							switch(mode) {
							case K_MAP:
								map.put(field.getName(), field.get(null));
								break;
							case V_MAP:
								map.put(field.get(null), field.getName());
								break;
							default:
							}
						} catch (Exception e) {
						}
					}
				}
			}
		}
		return map;
	}
}
